//
//  OAuthViewController.swift
//  WeiBo001
//
//  Created by Zhanghong on 15/6/28.
//  Copyright © 2015年 HeiMa. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController,UIWebViewDelegate {

    private let WB_Client_Id = "2840253673"
    private let WB_Redirect_Uri = "http://www.baidu.com"
    private let WB_App_Secret = "9dde0920f755135e720acfc4c63e86d6"
    
    lazy var webView: UIWebView? = {
       let v = UIWebView()
        v.delegate = self
        return v
    }()
    
    override func loadView() {
        view = webView
        title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        // 加载授权页面
        loadOAuthPage()
    }
    
///  加载授权页面
    private func loadOAuthPage(){
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_Client_Id)&redirect_uri=\(WB_Redirect_Uri)"
        let url = NSURL(string: urlString)!
        webView?.loadRequest(NSURLRequest(URL: url))
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL!.absoluteString
//        print("urlString:\(urlString)")
        // 如果不是回调地址
        if !urlString.hasPrefix(WB_Redirect_Uri){
            return true
        }
        
        let query = request.URL!.query!
        let codeStr = "code="
        
        if query.hasPrefix(codeStr){
            let code = query.substringFromIndex(advance(codeStr.endIndex, 0))
            print("获取授权码\(code)")
            loadAccessToken(code)
        }else{
            print("取消授权码")
            close()
        }
        
        
        return false
    }
    
    func loadAccessToken(code: String){
        let urlString = "oauth2/access_token"
        let params = ["client_id":WB_Client_Id,
            "client_secret" : WB_App_Secret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri":WB_Redirect_Uri
        ]
        
        
        
        // 设置数据响应格式-二进制
//        NetworkTools.shareNetworkTools().responseSerializer = AFHTTPResponseSerializer()
        
         NetworkTools.shareNetworkTools().POST(urlString, parameters: params, success: { (_, JSON) -> Void in
            
            // 加载用户信息
            UserAccount(dict: JSON as! [String : AnyObject]).loadUserInfo { (account, error) -> () in
                if account != nil {
//                    print(account)
                    shareAccount = account
                    NSNotificationCenter.defaultCenter().postNotificationName(HMSwitchRootVCNotification, object: false)
                    self.close()
                    return
                }
                print(error)
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
            }

            
            // 归档保存
//            account.saveAccount()
            
            
            }) { (_, error) -> Void in
                print(error)
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
        }
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showInfoWithStatus("正在玩命加载中。。。")
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func close(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
   
}
